#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   category.py
@Time    :   2024/01/03 20:02:14
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from ninja import Router, Field, ModelSchema, Query
from typing import Union, List
from django.forms import model_to_dict
from ninja.pagination import paginate
from django.db import transaction

from article.models import ArticleCategory
from utils.crud import create, delete, retrieve, update
from utils.response import R
from utils.auth import BaseFilters, MyPagination, get_user_info_from_token

router = Router()


class Filters(BaseFilters):
    cate_name: str = Field(None, alias="cate_name")
    cate_alias: str = Field(None, alias="cate_alias")
    id: str = Field(None, alias="id")


class SchemaIn(ModelSchema):
    class Config:
        model = ArticleCategory
        model_fields = ["cate_name", "cate_alias"]


class SchemaOut(ModelSchema):
    class Config:
        model = ArticleCategory
        model_fields = ["id", "cate_name", "cate_alias"]


# 获取分类列表
@router.get("/list", summary="获取分类", response=Union[List[SchemaOut], R])
def get_category(request, filters: Filters = Query(...)):
    cates = retrieve(request, ArticleCategory, filters)
    data = [SchemaOut(**model_to_dict(cate)) for cate in cates]
    return R.ok(data=data, msg="获取分类成功")


# 获取分类详情
@router.get("/info/{id}", summary="获取分类详情", response=Union[SchemaOut, R])
def get_category_detail(request, id: int, filters: Filters = Query(...)):
    filters.id = id
    cate = retrieve(request, ArticleCategory, filters)
    if not cate:
        return R.fail(msg="分类不存在")
    return R.ok(data=SchemaOut(**model_to_dict(cate[0])), msg="获取分类详情成功")


@router.post("/add", summary="增加分类", response=Union[SchemaOut, R])
def create_category(request, data: SchemaIn):
    try:
        # 从请求中获取用户信息
        request_user = get_user_info_from_token(request)
        # 验证该用户是否已有该分类
        if ArticleCategory.objects.filter(
            cate_name=data.cate_name, creator_id=request_user["id"]
        ).exists():
            return R.fail(msg="此分类已存在")
        with transaction.atomic():
            # 新增分类
            cata = create(request, data, ArticleCategory)
            data = SchemaOut(**model_to_dict(cata))
            return R.ok(data=data, msg="新增分类成功")
    except Exception as e:
        return R.fail(msg="新增分类失败")


@router.delete("/del/{id}", summary="删除分类", response=R)
def delete_category(request, id: int):
    try:
        # 从请求中获取用户信息
        request_user = get_user_info_from_token(request)
        # 验证该用户是否已有该分类
        if not ArticleCategory.objects.filter(
            id=id, creator_id=request_user["id"]
        ).exists():
            return R.fail(msg="要删除的分类不存在")
        delete(id, ArticleCategory)
        return R.ok(msg="删除分类成功")
    except Exception as e:
        return R.fail(msg="删除分类失败")


# 更新分类
@router.put("/info", summary="更新分类", response=Union[SchemaOut, R])
def update_category(request, data: SchemaOut):
    try:
        # 从请求中获取用户信息
        request_user = get_user_info_from_token(request)
        # 验证该用户是否已有该分类
        if ArticleCategory.objects.filter(
            id=data.id, creator_id=request_user["id"]
        ).exists():
            # 验证名称是否重复
            if (
                ArticleCategory.objects.filter(
                    cate_name=data.cate_name, creator_id=request_user["id"]
                )
                .exclude(id=data.id)
                .exists()
            ):
                return R.fail(msg="此分类已存在")
            with transaction.atomic():
                update(request, data.id, data, ArticleCategory)
                return R.ok(data=data, msg="更新分类成功")
        else:
            return R.fail(msg="要更新的分类不存在")
    except Exception as e:
        return R.fail(msg="更新分类失败")
